// pages/time-wage/time-wage.js
const app = getApp()

Page({
  data: {
    wageData: {},
    loading: true,
    currentMonth: '',
    currentYear: ''
  },

  onLoad: function (options) {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = (now.getMonth() + 1).toString().padStart(2, '0')
    
    this.setData({
      currentYear: currentYear,
      currentMonth: currentMonth
    })
    
    this.loadWageData()
  },

  onShow: function () {
    this.loadWageData()
  },

  // 加载工资数据
  loadWageData: function () {
    this.setData({ loading: true })

    app.request({
      url: '/getTimeWage',
      method: 'GET'
    }).then((res) => {
      if (res.code === 1) {
        const wageList = res.data || []
        // 计算汇总数据
        const totalWage = wageList.reduce((sum, item) => sum + (item.total_wage || 0), 0)
        const totalHours = wageList.reduce((sum, item) => sum + (item.total_hours || 0), 0)
        const avgHourlyRate = totalHours > 0 ? (totalWage / totalHours).toFixed(2) : 0
        
        this.setData({
          wageData: {
            list: wageList,
            total_wage: totalWage,
            total_hours: totalHours,
            avg_hourly_rate: avgHourlyRate,
            task_count: wageList.length
          },
          loading: false
        })
      }
    }).catch((err) => {
      console.error('加载工资数据失败:', err)
      this.setData({ loading: false })
    })
  },

  // 选择月份
  onMonthChange: function (e) {
    const value = e.detail.value
    const [year, month] = value.split('-')
    
    this.setData({
      currentYear: year,
      currentMonth: month
    })
    
    this.loadWageData()
  }
})
